package cn.dakaqi.apps.group.admin.controller;

import cn.dakaqi.apps.group.admin.utils.FileOperateUtil;
import cn.dakaqi.apps.group.admin.utils.VolunteerInfoExcel;
import cn.dakaqi.entities.Group;
import cn.dakaqi.entities.GroupVolunteer;
import cn.dakaqi.entities.user.User;
import cn.dakaqi.entities.user.Volunteer;
import cn.dakaqi.entities.user.VolunteerCertification;
import cn.dakaqi.services.GroupService;
import cn.dakaqi.services.GroupVolunteerService;
import cn.dakaqi.services.user.UserService;
import cn.dakaqi.services.user.VolunteerCertificationService;
import cn.dakaqi.services.user.VolunteerService;
import cn.dakaqi.utils.Clock;
import cn.dakaqi.utils.DKQConstant;
import cn.dakaqi.utils.JsonResult;
import cn.dakaqi.utils.UUIDHexGenerator;
import cn.dakaqi.utils.exception.ServiceRuntimeException;
import com.mangofactory.swagger.annotations.ApiIgnore;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.ServletRequestUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import org.springframework.web.servlet.view.RedirectView;
import org.springside.modules.web.MediaTypes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by chunyang on 2016/5/9.
 */
@Controller
@RequestMapping(value = "/volunteer")
@ApiIgnore
public class VolunteerController extends BaseController
{
    @Autowired
    UserService userService;
    @Autowired
    VolunteerService volunteerService;
    @Autowired
    GroupService groupService;
    @Autowired
    GroupVolunteerService groupVolunteerService;
    @Autowired
    VolunteerCertificationService volunteerCertificationService;


    @Override
    protected ModelAndView initModelAndView(String groupCode, String view, HttpServletRequest request)
    {
        ModelMap modelMap = super.initData(groupCode, request);
        return new ModelAndView(view, modelMap);
    }

    @Override
    protected void clearModelAndView(String groupCode, HttpServletRequest request)
    {

    }

    private Group getCurGroup(HttpServletRequest request)
    {
        return ((Group) request.getSession().getAttribute("curGroup"));
    }

    @RequestMapping(method = RequestMethod.GET)
    public ModelAndView list(
            @RequestParam(value = "page", defaultValue = "1") int pageNumber,
            @RequestParam(value = "page.size", defaultValue = PAGE_SIZE) int pageSize,
            @RequestParam(value = "sortType", defaultValue = "auto") String sortType,
            @RequestParam(value = "status", defaultValue = "2") int status, HttpServletRequest request)
    {
        String view = "volunteer/index";
        Group curGroup = getCurGroup(request);
        modelAndView = initModelAndView(curGroup.getGroupCode(), view, request);

        //查询当前社团所有成员
        Page<GroupVolunteer> data = groupVolunteerService.queryGroupCode(curGroup.getGroupCode(), status, pageNumber);
        modelAndView.addObject("data", data);
        modelAndView.addObject("status", 2);
        return modelAndView;
    }

    @RequestMapping(value = "/searchByName", method = RequestMethod.GET)
    public ModelAndView searchByName(@RequestParam("name") String name, HttpServletRequest request)
    {
        String view = "volunteer/index";
        Group curGroup = getCurGroup(request);
        modelAndView = initModelAndView(curGroup.getGroupCode(), view, request);
        //查询当前社团所有成员
        Page<GroupVolunteer> data = groupVolunteerService.findNameLike(curGroup.getGroupCode(), name);
        modelAndView.addObject("data", data);
        return modelAndView;
    }

    @RequestMapping(value = "/searchByJob", method = RequestMethod.GET)
    public ModelAndView searchByJob(@RequestParam("job") String job, HttpServletRequest request)
    {
        String view = "volunteer/index";
        Group curGroup = getCurGroup(request);
        modelAndView = initModelAndView(curGroup.getGroupCode(), view, request);
        //查询当前社团所有成员
        Page<GroupVolunteer> data = groupVolunteerService.findByJob(curGroup.getGroupCode(), job);
        modelAndView.addObject("data", data);
        modelAndView.addObject("job", job);
        return modelAndView;
    }

    @RequestMapping(value = "/searchBySkill", method = RequestMethod.GET)
    public ModelAndView searchBySkill(@RequestParam("skill") String skill, HttpServletRequest request)
    {
        String view = "volunteer/index";
        Group curGroup = getCurGroup(request);
        modelAndView = initModelAndView(curGroup.getGroupCode(), view, request);
        //查询当前社团所有成员
        Page<GroupVolunteer> data = groupVolunteerService.findBySkill(curGroup.getGroupCode(), skill);
        modelAndView.addObject("data", data);
        modelAndView.addObject("skill", skill);
        return modelAndView;
    }

    @RequestMapping(value = "/searchByStatus", method = RequestMethod.GET)
    public ModelAndView searchByStatus(@RequestParam(value = "status",defaultValue = "2") int status, HttpServletRequest request)
    {
        String view = "volunteer/index";
        Group curGroup = getCurGroup(request);
        System.out.println("curGroup--------->"  +curGroup);
        modelAndView = initModelAndView(curGroup.getGroupCode(), view, request);
        //查询当前社团所有成员
        Page<GroupVolunteer> data = groupVolunteerService.findByStatus(curGroup.getGroupCode(), status);
        modelAndView.addObject("data", data);
        modelAndView.addObject("status", status);
        return modelAndView;
    }

    @RequestMapping(value = "/searchByServiceField", method = RequestMethod.GET)
    public ModelAndView searchByServiceField(@RequestParam("serviceField") String serviceField, HttpServletRequest request)
    {
        String view = "volunteer/index";
        Group curGroup = getCurGroup(request);
        modelAndView = initModelAndView(curGroup.getGroupCode(), view, request);
        //查询当前社团所有成员
        Page<GroupVolunteer> data = groupVolunteerService.findByServiceField(curGroup.getGroupCode(), serviceField);
        modelAndView.addObject("data", data);
        modelAndView.addObject("serviceField", serviceField);
        return modelAndView;
    }

    @RequestMapping(value = "/reg", method = RequestMethod.GET)
    public ModelAndView createForm(HttpServletRequest request)
    {
        String view = "volunteer/volunteerForm";
        Group curGroup = getCurGroup(request);
        ModelAndView modelAndView = initModelAndView(curGroup.getGroupCode(), view, request);
        modelAndView.addObject("newVolunteer", new Volunteer());
        modelAndView.addObject("action", "/reg");
        return modelAndView;
    }

    @RequestMapping(value = "/reg", method = RequestMethod.POST)
    public RedirectView reg(@ModelAttribute("volunteer") Volunteer newVolunteer, HttpServletRequest request, RedirectAttributes redirectAttributes)
    {
        Group curGroup = getCurGroup(request);
        this.userService.regUser(newVolunteer, curGroup.getGroupCode());
        String url = request.getContextPath() + "/volunteer/reg?groupCode=" + curGroup.getGroupCode();
        redirectAttributes.addFlashAttribute("message", "注册成功");
        redirectAttributes.addFlashAttribute("newVolunteer", newVolunteer);
        return new RedirectView(url);
    }

    @RequestMapping(value = "/wait-verifer", method = RequestMethod.GET)
    public ModelAndView waitVerifer(HttpServletRequest request)
    {
        String view = "volunteer/wait-verfier";
        Group curGroup = getCurGroup(request);
        Page<GroupVolunteer> data = this.groupVolunteerService.findByGroup(curGroup.getGroupCode(), 1, DKQConstant.USER_UNLOCK);
        ModelAndView modelAndView = initModelAndView(curGroup.getGroupCode(), view, request);
        modelAndView.addObject("data", data);
        return modelAndView;
    }

    @RequestMapping(value = "/realVerfier/{memberCoce}", method = RequestMethod.GET)
    public ModelAndView realVerfier(@PathVariable("memberCoce") String memberCoce, HttpServletRequest request)
    {
        String view = "volunteer/realVerfier";
        Group curGroup = getCurGroup(request);
        VolunteerCertification certification = volunteerCertificationService.findByMemberCode(memberCoce);
        ModelAndView modelAndView = initModelAndView(curGroup.getGroupCode(), view, request);
        modelAndView.addObject("certification", certification);
        return modelAndView;
    }

    @RequestMapping(value = "/verfier", method = RequestMethod.POST)
    public ResponseEntity<?> verfier(@RequestParam("memberCode") String memberCode, @RequestParam("status") int status, HttpServletRequest request)
    {
        JsonResult jsonResult = new JsonResult();
        String message = "审核成功";
        try
        {
            Volunteer volunteer = (Volunteer) request.getSession().getAttribute("volunteer");
            volunteerCertificationService.updateStatus(memberCode, status, volunteer.getMemberCode());
            jsonResult.setCode(JsonResult.CODE_SUCCESS);
            jsonResult.setMessage(message);
        } catch (ServiceRuntimeException e)
        {
            e.printStackTrace();
            message = e.getMessage();
            jsonResult.setCode(JsonResult.CODE_FAIL);
            jsonResult.setMessage(message);
        } catch (Exception e)
        {
            e.printStackTrace();
            message = "审核失败";
            jsonResult.setCode(JsonResult.CODE_FAIL);
            jsonResult.setMessage(message);
        }

        return new ResponseEntity(jsonResult, HttpStatus.OK);
    }

    @RequestMapping(value = "/detail/{memberCode}", method = RequestMethod.GET)
    public ModelAndView detail(@PathVariable("memberCode") String memberCode, HttpServletRequest request)
    {
        String view = "volunteer/detail";
        Group curGroup = getCurGroup(request);
        ModelAndView modelAndView = initModelAndView(curGroup.getGroupCode(), view, request);
        Volunteer volunteer = this.volunteerService.findByMemberCode(memberCode);
        modelAndView.addObject("otherVolunteer", volunteer);
        return modelAndView;
    }

    @RequestMapping(value = "/importPage", method = RequestMethod.GET)
    public ModelAndView importPage(HttpServletRequest request)
    {
        String view = "volunteer/importVolunteer";
        Group curGroup = getCurGroup(request);
        modelAndView = initModelAndView(curGroup.getGroupCode(), view, request);
        return modelAndView;
    }

    @RequestMapping("/importExcel")
    public ResponseEntity<?> importBuildInfoExcel(HttpServletRequest request, HttpServletResponse response)
    {
        JsonResult jsonResult = new JsonResult();
        try
        {
            Map<String, Object> map = new HashMap<String, Object>();
            // 别名
            String[] alaises = ServletRequestUtils.getStringParameters(request,"alais");
            String[] params = new String[] { "alais" };
            Map<String, Object[]> values = new HashMap<String, Object[]>();
            values.put("alais", alaises);
            List<Map<String, Object>> result = FileOperateUtil.upload(request, params, values);
            List<Volunteer> list= VolunteerInfoExcel.importVolunteerInfo(new File(String.valueOf(result.get(0).get(FileOperateUtil.UPLOADFilePath))), request);//这里是解析excel文件
            Group curGroup = getCurGroup(request);
            importData(curGroup,list);
            map.put("result", list);
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }

        return new ResponseEntity(jsonResult, HttpStatus.OK);
    }
    @RequestMapping(value = "/freeze", method = RequestMethod.POST,produces = MediaTypes.JSON_UTF_8)
    public ResponseEntity<?> freeze(@RequestParam("id") long id,@RequestParam("status") int status,HttpServletRequest request)
    {
        JsonResult jsonResult = new JsonResult();
        Volunteer volunteer = (Volunteer) request.getSession().getAttribute("volunteer");
        this.groupVolunteerService.freeze(id,status,volunteer.getMemberCode(),"经常报名不参加活动");
        jsonResult.setCode(JsonResult.CODE_SUCCESS);
        jsonResult.setMessage("操作成功");
        return new ResponseEntity(jsonResult, HttpStatus.OK);
    }

    @RequestMapping("/excel")
    public String viewExcel(ModelMap modelMap,@RequestParam(value = "status",defaultValue = "2") int status,
                            HttpServletRequest request,HttpServletResponse response) {
        Group curGroup = getCurGroup(request);
        List<Volunteer> vos = new ArrayList<Volunteer>();
        Page<GroupVolunteer> data = groupVolunteerService.queryGroupCode(curGroup.getGroupCode(), status, 1);
        if(null != data && data.getContent() != null && data.getContent().size()>0)
        {
            for(GroupVolunteer groupVolunteer:data.getContent())
            {
                vos.add(groupVolunteer.getVolunteer());
            }
            for(int i=2;i<=data.getTotalPages();i++)
            {
                data = groupVolunteerService.queryGroupCode(curGroup.getGroupCode(), status,i);
                if(null != data && data.getContent() != null && data.getContent().size()>0)
                {
                    for(GroupVolunteer groupVolunteer:data.getContent())
                    {
                        vos.add(groupVolunteer.getVolunteer());
                    }
                }
            }
        }


        String[] title = new String [8];
        title[0] = "姓名";
        title[1] = "手机";
        title[2] = "性别";
        title[3] = "服务领域";
        title[4] = "职业";
        title[5] = "技能";
        title[6] = "证件类型";
        title[7] = "证件号";


        modelMap.put("list", vos);
        modelMap.put("fileName","志愿者信息.xls");
        modelMap.put("sheetName","志愿者信息");
        modelMap.put("title",title);
        return "volunteer-record-list";
    }

    private List<Volunteer> findAllMembers(String groupCode,int pageNumber)
    {
        List<Volunteer> vos = new ArrayList<Volunteer>();
        Page<GroupVolunteer> data = groupVolunteerService.queryGroupCode(groupCode, DKQConstant.APPLY_STATUS_OK, pageNumber);
        if(null != data && data.getContent() != null && data.getContent().size()>0)
        {
            for(GroupVolunteer groupVolunteer:data.getContent())
            {
                vos.add(groupVolunteer.getVolunteer());
            }
        }
        return vos;
    }
    private void importData(Group group,List<Volunteer> list)
    {
        if(null != list && list.size()>0)
        for(Volunteer v:list)
        {
            User user = new User();
            user.setMobile(v.getMobile());
            user.setPassword("123456");
            user.setRealName(v.getRealName());
            user.setNickName(v.getRealName());
            user.setRoles("user");
            user.setEmail(v.getMobile() + "@dakaqi.cn");
            user.setPlatform(DKQConstant.USER_PLATFORM_WEB);
            user.setCreateTime(Clock.DEFAULT.getCurrentDate());
            user.setDelStatus(DKQConstant.DEL_NO);
            user.setLocked(DKQConstant.USER_UNLOCK);
            user.setOldID(0L);
            user.setOldMemberCode("");
            this.userService.saveSimpleUser(user);

            v.setMemberCode(UUIDHexGenerator.generator());
            v.setCrateTime(Clock.DEFAULT.getCurrentDate());
            v.setMobile(user.getMobile());
            v.setNickName(user.getNickName());
            v.setRealName(user.getRealName());
            v.setUserId(user.getId());
            v.setHeadUrl(DKQConstant.HEAR_URL);
            v.setTimes(0L);
            v.setSex(getSexFromCardNO(v.getCardNO()));
            v.setBirthDay(getBirthFromCardNO(v.getCardNO()));
            v.setResidenceAddress(v.getProvince()+"-" + v.getCity() + "-" + v.getDistrict());
            this.volunteerService.saveVolunteer(v);

            GroupVolunteer groupVolunteer = new GroupVolunteer();
            groupVolunteer.setDelStatus(DKQConstant.DEL_NO);
            groupVolunteer.setStatus(DKQConstant.APPLY_STATUS_OK);
            groupVolunteer.setCreateTime(Clock.DEFAULT.getCurrentDate());
            groupVolunteer.setTimes(0L);
            groupVolunteer.setGroup(group);
            groupVolunteer.setRole(DKQConstant.ROLES_VOLUNTEER);
            groupVolunteer.setVolunteer(v);

            groupVolunteerService.importData(groupVolunteer);
        }
    }

    private String getBirthFromCardNO(String icard)
    {
        int len = icard.length();
        StringBuilder ymd = new StringBuilder();
        switch (len)
        {
            case 15:

                ymd.append("19").append(icard.substring(6, 12));
                break;
            case 18:
                ymd.append(icard.substring(6, 14));
                break;
            default:
                return "2010-01-01";
        }
        return ymd.substring(0, 4) + "-" + ymd.substring(4, 6) + "-" + ymd.substring(6, 8);
    }

    private String getSexFromCardNO(String icard)
    {
        int len = icard.length();
        String sex = "男";
        switch (len)
        {
            case 15:
                //String birth1 = icard.substring(6, 12);
                sex = icard.substring(14, 15);
                if (Integer.parseInt(sex) % 2 == 0)
                {
                    sex = "女";
                } else
                {
                    sex = "男";

                }
                break;
            case 18:
                //String birth2 = icard.substring(6, 14);
                sex = icard.substring(16, 17);
                if (Integer.parseInt(sex) % 2 == 0)
                {
                    sex = "女";
                } else
                {
                    sex = "男";

                }
                break;
        }
        return sex;
    }
}
